<template>
  <div>
    <van-nav-bar
      :title="msg"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="goodsImgWrap">
      <img :src="goodsImgUrl" />
    </div>
    <p>{{ goodsTitle }}，{{ description }} ${{ price }}</p>

    <van-sku
      v-model="showBase"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :hide-stock="sku.hide_stock"
      :quota-used="0"
      :reset-stepper-on-hide="false"
      :reset-selected-sku-on-hide="false"
      :close-on-click-overlay="true"
      :disable-stepper-input="false"
      :message-config="{}"
      @sku-selected="switchProductType"
      @add-cart="onAddCartFn"
    />

    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" @click="onHelpBtn" />
      <van-goods-action-icon
        icon="chat-o"
        text="购物车"
        :badge="goodsCnt"
        @click="gotoCartBtn"
      />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="addCartFn"
      />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>
<script>
import axios from "axios";
import API_LIST from "@/APIList.config";
import footerBar from "./footerBar";
export default {
  name: "goodsProduct",
  data() {
    return {
      msg: "商品详情页",
      goodsTitle: "",
      goodsImgUrl: "",
      description: "",
      price: "",
      showBase: false,
      goods: {},
      goodsId: "",
      goodsCnt: 0,
      sku: {
        tree: [
          {
            k: "产品类型", // skuKeyName：规格类目名称
            v: [
              {
                id: "30349", // skuValueId：规格值 id
                name: "红色", // skuValueName：规格值名称
                imgUrl: "https://img.yzcdn.cn/1.jpg", // 规格类目图片，只有第一个规格类目可以定义图片
              },
              {
                id: "1215",
                name: "蓝色",
                imgUrl: "https://img.yzcdn.cn/2.jpg",
              },
            ],
            k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
          },
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId，下单时后端需要
            price: "", // 价格（单位分）
            s1: "1215", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1193", // 规格类目 k_s 为 s2 的对应规格值 id
            s3: "0", // 最多包含3个规格值，为0表示不存在该规格
            stock_num: 110, // 当前 sku 组合对应的库存
          },
        ],
        price: "", // 默认价格（单位元）
        stock_num: 227, // 商品总库存
        hide_stock: false, // 是否隐藏剩余库存
      },
    };
  },
  created() {
    // console.log(this.$route.query._goodsObjId);
    let goodsId = this.$route.query._goodsObjId;
    let collectionName = this.$route.query._collectionName;
    this.getGoodsInfoFn(goodsId, collectionName);

    this.goodsId = goodsId;
    var xx = localStorage.cartDataInfo
      ? JSON.parse(localStorage.cartDataInfo)
      : [];
    // console.log(xx);
    // localStorage.removeItem('cartDataInfo')
    this.computeAllGoodsCntFn();
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    getGoodsInfoFn(goodsId, collectionName) {
      axios
        .get(API_LIST.getGoodsInfo, {
          params: {
            _id: goodsId,
            _c: collectionName,
          },
        })
        .then((_d) => {
          //   console.log(_d.data);
          this.goodsTitle = _d.data.name;
          this.goodsImgUrl = _d.data.img;
          this.description = _d.data.describe;
          this.price = _d.data.price;

          //   this.goods.title = _d.data.name;
          this.goods.picture = _d.data.img;
          this.sku.price = _d.data.price;
        });
    },
    addCartFn() {
      this.showBase = true;
    },
    switchProductType() {
      this.sku.list[0].price = this.sku.price;
    },
    onAddCartFn(_d) {
      // console.log(_d);
      let _istrue = false;

      let _tempObj = {
        _id: _d.goodsId,
        _price: this.price,
        _num: _d.selectedNum,
        _goodsName: this.goodsTitle,
        _img: this.goodsImgUrl,
      };
      var _cart = localStorage.cartDataInfo
        ? JSON.parse(localStorage.cartDataInfo)
        : [];
      for (let i = 0; i < _cart.length; i++) {
        if (_cart[i]._id === _tempObj._id) {
          _istrue = true;
          _cart[i]._num += _tempObj._num;
          break;
        }
      }
      if (!_istrue) {
        _cart.push(_tempObj);
      }
      //   console.log(_tempObj);
      localStorage.cartDataInfo = JSON.stringify(_cart);
      this.$dialog
        .alert({
          message: "加入购物车成功",
        })
        .then(() => {
          this.showBase = false;
          this.computeAllGoodsCntFn();
        });
    },
    gotoCartBtn() {
      this.$router.push({ path: "/cart" });
    },
    computeAllGoodsCntFn() {
      let _cart = localStorage.cartDataInfo
        ? JSON.parse(localStorage.cartDataInfo)
        : [];
      let _n = 0;
      for (let i = 0; i < _cart.length; i++) {
        _n += _cart[i]._num;
        this.goodsCnt = _n;
      }
    },
    onHelpBtn() {
      this.$dialog.alert({
        message: "客服正忙，请稍后",
      });
    },
  },
};
</script>
<style scoped>
.goodsImgWrap {
  width: 100%;
  height: 350px;
  overflow: hidden;
  margin: 0 auto;
}
.goodsImgWrap img {
  width: 100%;
  height: 350px;
}
</style>